import { useRef, useState } from 'react'
import Editor, { OnMount } from '@monaco-editor/react'
import * as monaco from 'monaco-editor'
import { Button, Layout, Typography } from 'antd'
import mathLabTypes from '../../../../scriptEngine/mathLab.d.ts?raw'
import {logger} from '../../utils/logger'
const { Header, Content } = Layout
const { Title, Text } = Typography

const ScriptEditor: React.FC = () => {
  const [code, setCode] = useState(
    '// 在这里输入 JavaScript 代码\nconsole.log("Hello, Electron!");\n"hello"'
  )
  const [output, setOutput] = useState<string>('')

  // 运行 JS 代码
  const executeScript = async () => {
    const result = await (window as any).electronAPI.executeScript(code)
    setOutput(result.success ? String(result.output) : `错误: ${result.error}`)
  }
  const runCode: () => Promise<void> = async () => {
    const tt = new Date(Date.now() + 8 * 3600 * 1000)
    .toISOString()
    .replace('T', ' ')
    .replace(/\.(\d{3})Z/, '.$1');
    // const times=tt.replace(/T/, ' ').replace(/(\d{2}:\d{2}:\d{2}).(\d{3})Z/, '$1.$2')
    console.log(tt)
    const result = await (window as any).electronAPI.runScript(code)
    if (result.success) {
      logger.info('脚本执行成功', {
        output: result.output
      })
    }else{
      logger.error('脚本执行失败', {
        error: result.output
      })
    }
    setOutput(result.success ? String(result.output) : `错误: ${result.output}`)
  }

  //add javascript autocomplete for monaco editor
  const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);

  // 代码编辑器初始化
  const handleEditorMount: OnMount = (editor, monaco) => {
    editorRef.current = editor;

    // 💡 注册自定义函数和数据类型
    registerCustomFunctions(monaco);
  };

  return (
    <Layout style={{ height: '100%' }}>
      <Header style={{ color: '#fff', textAlign: 'center', fontSize: 20 }}>
        Electron JavaScript 引擎
      </Header>
      <Content style={{ display: 'flex' }}>
        {/* 左侧代码编辑器 */}
        <div
          style={{
            flex: 1,
            padding: 10,
            borderRight: '1px solid #ddd',
            height: '100%',
            display: 'flex',
            flexDirection: 'column'
          }}
        >
          <div style={{ display: 'flex' }}>
            <Title level={4}>JavaScript 编辑器</Title>
            <div style={{ flexGrow: 1 }} />
            <Button type="default" onClick={runCode} style={{ marginRight: 5 }}>
              运行代码（VM）
            </Button>
            <Button type="dashed" onClick={executeScript} style={{ marginLeft: 5 }}>
              运行代码（独立进程）
            </Button>
          </div>
          <Editor
            // theme="vs-dark"
            language="javascript"
            options={{
              minimap: { enabled: false },
              fontSize: 14,
              wordWrap: 'on',
              automaticLayout: true,
              scrollBeyondLastLine: false
            }}
            height="100%"
            defaultLanguage="javascript"
            value={code}
            onMount={handleEditorMount}
            onChange={(value) => setCode(value || '')}
          />
        </div>

        {/* 右侧输出窗口 */}
        <div style={{ flex: 1, padding: 10, display: 'flex', flexDirection: 'column' }}>
          <Title level={4}>执行结果</Title>
          <Text
            type="secondary"
            style={{ overflowY: 'auto', flexGrow: 1, background: '#fff', padding: 10 }}
          >
            <pre>{output}</pre>
          </Text>
        </div>
      </Content>
    </Layout>
  )
}

const registerCustomFunctions = (monaco: typeof import('monaco-editor')) => {
  // 1️⃣ **添加自动补全提示**
  // monaco.languages.registerCompletionItemProvider('javascript', {
  //   provideCompletionItems: (model, position) => {
  //     const suggestions: monaco.languages.CompletionItem[] = [
  //       {
  //         label: 'myAdd',
  //         kind: monaco.languages.CompletionItemKind.Function,
  //         insertText: 'myAdd(${1:arg1}, ${2:arg2})',
  //         insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
  //         detail: '自定义加法函数 myAdd(a: number, b: number): number',
  //         range: undefined
  //       },
  //       {
  //         label: 'User',
  //         kind: monaco.languages.CompletionItemKind.Class,
  //         insertText: 'User',
  //         detail: '自定义类型 User { id: number, name: string }',
  //         range: undefined
  //       }
  //     ]
  //     return { suggestions }
  //   }
  // })

  // 2️⃣ **添加 TypeScript 类型定义**
  // const customTypes = `
  //   declare function myAdd(a: number, b: number): number;

  //   interface User {
  //     id: number;
  //     name: string;
  //   }
  // `

  // monaco.languages.typescript.javascriptDefaults.addExtraLib(mathLabTypes, 'ts:custom-types.d.ts')
  monaco.languages.typescript.javascriptDefaults.addExtraLib(mathLabTypes)

  console.log('🔹 自定义函数和类型已注册到 Monaco Editor')
}

export default ScriptEditor
